package vn.edu.ptithcm.pim.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.ParameterizableViewController;

import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.Application;
import vn.edu.ptithcm.pim.service.UserService;

public class MyHomePageController extends ParameterizableViewController {
	private UserService userService;
	Logger log = Logger.getLogger(MyHomePageController.class);

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> bean = new HashMap<String, Object>();
		if (userService.isSignedIn(request)) {
			String loginName = userService.getCurrentLogin(request);
			bean.put("user", userService.findByLoginName(loginName));
			bean.put("isSigned", true);
			bean.put(Constants.LOGIN_NAME, loginName);
			bean.put(Constants.USER_NAME, userService.getUsername(loginName));

			@SuppressWarnings("unchecked")
			List<Application> applications = userService
					.getApplications(loginName);
			String selectedPage = "";
			String viewURL = request.getRequestURI();
			for (Application p : applications) {
				String friendlyUrl = p.getFriendlyurl();
				if (viewURL.indexOf(friendlyUrl) != -1) {
					selectedPage = friendlyUrl;
					break;
				}
			}
			log.info("number of apps of user :" + applications.size());
			bean.put("selectedPage", selectedPage);
			bean.put("applications", applications);
		} else {
			String redirectLink = UrlConstants.MY_HOME_PAGE_URL
					+ UrlConstants.HTM;
			request.getSession().setAttribute("redirectLink", redirectLink);
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}
		return new ModelAndView(UrlConstants.MY_HOME_PAGE_URL, "bean", bean);
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
